package com.usian.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.usian.mapper.*;
import com.usian.mq.MQSender;
import com.usian.pojo.*;
import com.usian.redis.RedisClient;
import com.usian.service.OrderService;
import com.usian.utils.JsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author chen
 * @date 2021/1/27 - 23:35 - 星期三
 * @project usian_parent
 * @package com.usian.service.Impl
 * @by GGbomd猪猪侠
 */
@Service
public class OrderServiceImpl implements OrderService {

    @Value("${ORDER_ID_KEY}")
    private String ORDER_ID_KEY;

    //订单号
    @Value("${ORDER_ID_BEGIN}")
    private Long ORDER_ID_BEGIN;

    @Value("${ORDER_ITEM_ID_KEY}")
    private String ORDER_ITEM_ID_KEY;

    @Autowired
    private RedisClient redisClient;

    @Autowired
    private TbOrderMapper tbOrderMapper;

    @Autowired
    private TbOrderItemMapper tbOrderItemMapper;

    @Autowired
    private TbOrderShippingMapper tbOrderShippingMapper;

    @Autowired
    private MQSender mqSender;

    @Autowired
    private TbItemMapper tbItemMapper;

    @Autowired
    private LocalMessageMapper localMessageMapper;

    @Override
    public String insertOrder(OrderInfo orderInfo) {
        // 解析orderInfo 把刚刚封装进去的参数拿出来
        TbOrder tbOrder = orderInfo.getTbOrder();
        TbOrderShipping tbOrderShipping = orderInfo.getTbOrderShipping();
        List<TbOrderItem> tbOrderItemList = JsonUtils.jsonToList(orderInfo.getOrderItem(), TbOrderItem.class);

        //保存订单信息  判断redis里有没有这个订单信息的key
        if(!redisClient.exists(ORDER_ID_KEY)){
            redisClient.set(ORDER_ID_KEY,ORDER_ID_BEGIN);
        }
        // 自增每次自增1
        Long orderId = redisClient.incr(ORDER_ID_KEY, 1L);
        //  补齐剩下的数据
        tbOrder.setOrderId(orderId.toString());
        Date date = new Date();
        tbOrder.setCreateTime(date);
        tbOrder.setUpdateTime(date);
        //1、未付款，2、已付款，3、未发货，4、已发货，5、交易成功，6、交易关闭
        tbOrder.setStatus(1); //默认为1未付款
        tbOrderMapper.insert(tbOrder);

        //3、保存明细信息
        if(!redisClient.exists(ORDER_ITEM_ID_KEY)){
            redisClient.set(ORDER_ITEM_ID_KEY,0);
        }
        for (int i = 0; i < tbOrderItemList.size(); i++) {
            Long oderItemId = redisClient.incr(ORDER_ITEM_ID_KEY, 1L);
            TbOrderItem tbOrderItem =  tbOrderItemList.get(i);
            tbOrderItem.setId(oderItemId.toString());
            tbOrderItem.setOrderId(orderId.toString());
            tbOrderItemMapper.insert(tbOrderItem);
        }


        //4、保存物流信息
        tbOrderShipping.setOrderId(orderId.toString());
        tbOrderShipping.setCreated(date);
        tbOrderShipping.setUpdated(date);
        tbOrderShippingMapper.insert(tbOrderShipping);

        //保存本地消息记录
        LocalMessage localMessage = new LocalMessage();
        localMessage.setTxNo(UUID.randomUUID().toString());
        localMessage.setOrderNo(orderId.toString());
        localMessage.setState(0);
        localMessageMapper.insert(localMessage);

        //发布消息到mq，完成扣减库存     交换机名称           key          发送的消息体
        //amqpTemplate.convertAndSend("order_exchange","order.add", orderId);

        //发布消息到mq，完成扣减库存
        mqSender.sendMsg(localMessage);

        //返回订单id
        return orderId.toString();
    }

    /**
     * 查询超市订单
     * @return
     */
    @Override
    public List<TbOrder> selectOverTimeTbOrder() {
        return tbOrderMapper.selectOverTimeTbOrder();
    }

    /**
     * 关闭超市订单
     * @param tbOrder
     */
    @Override
    public void updateOverTimeTbOrder(TbOrder tbOrder) {
        tbOrder.setStatus(6);
        Date date = new Date();
        tbOrder.setCloseTime(date);
        tbOrder.setEndTime(date);
        tbOrder.setUpdateTime(date);
        tbOrderMapper.updateById(tbOrder);
    }

    /**
     * 把超市订单中的商品数量加回去
     * @param orderId
     */
    @Override
    public void updateTbItemByOrderId(String orderId) {
        //1、通过orderId查询LisT<TbOrderItem>
        QueryWrapper<TbOrderItem> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id",orderId);
        List<TbOrderItem> tbOrderItems = tbOrderItemMapper.selectList(queryWrapper);
        for (int i = 0; i < tbOrderItems.size(); i++) {
            TbOrderItem tbOrderItem = tbOrderItems.get(i);
            // 修改商品库存
            TbItem tbItem = tbItemMapper.selectByPrimaryKey(Long.valueOf(tbOrderItem.getItemId()));
            tbItem.setNum(tbItem.getNum()-tbOrderItem.getNum());
            tbItem.setUpdated(new Date());
            tbItemMapper.updateByPrimaryKey(tbItem);
        }
    }
}
